import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, Alert
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { RangTime } from '../../../component/common/RangTime.js';
import { ApproveRefuseModal } from '../../order/approve/details/modals/refuse';
import ToastUtil from '../../../utils/toast';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { NewAccountHome } from '../../../components/common/newAccountHome';
import { ProgressModal } from '../../../components/common/ProgressModal';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';
const scale = GLOBAL.SCALE;

export class clientFundsList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		let { selectAccount } = navigation.state.params || {};
		return {
			headerTitle: '客户资金列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (navigation.state.params && navigation.state.params.options <= 1 ?
				<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} /> :
				<View style={{ marginRight: 10 * scale }}>
					<NewAccount fn={(val) => {
						selectAccount && selectAccount()
					}}
						accountStyles={{ paddingTop: 8 * scale, paddingRight: 0 * scale }}
						imgUrl={require('../../../imgs/downAccount2.png')}
						imgStyle={{
							width: 12*scale,
							height: 12*scale,
						}}
						choice={navigation.state.params && navigation.state.params.choice ? navigation.state.params.choice.corpName : ''} />
				</View>
			),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			status: 'data',
			companyIndex: 0,
			// showTimeModal: false, // 时间选择
			refreshIcon: false, // 下拉刷新图标
			listData: [], // 列表数据
			saleCount: 0,
			purchaseCount: 0,
			refuseModalVisible: false,
			alertShow: false,
			options: [],
			choice: {
			},
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数
		this.taskId = '';
		this.pageParams = { // TODO
			pageNo: 1,
			pageSize: 10,
		}
	}

	async componentWillMount() {
		let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
		console.log(userInfo.corpInfoTOs)
		if (userInfo) {
			userInfo = JSON.parse(userInfo);
			this.setState({
				options: userInfo.corpInfoTOs || [],
				choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
			})
			this.props.navigation.setParams({
				options: userInfo.corpInfoTOs || [],
				choice: userInfo.corpInfoTOs[0]
			});
		}
		await this.initPage();
	}
	componentDidMount() {
		this.props.navigation.setParams({
			selectAccount: this._selectAccount
		});
	}

	_selectAccount = async () => {
		this.setState({
			alertShow: !this.state.alertShow
		})
	}
	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let { corpId } = this.state.options[this.state.companyIndex] || {};
		this.pageParams.corpId = corpId || '';
		let res = await HTTP.POST(API_GENERATE(API.COMPANY_LIST), this.pageParams);
		console.log(res)
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	// 刷新页面
	reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 下拉刷新
	refresh() {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.initPage();
	}

	// 上拉翻页
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}
	_renderSearchWarp = () => {
		const searchIcon = require('../../../imgs/global/whiteSearch.png');
		return (
			<View style={styles.filterWrap}>
				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="orderKeywordsInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入企业名称"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.pageParams.searchCode}
						onChangeText={(txt) => { this.pageParams.searchCode = txt; }}
						onSubmitEditing={() => { this.refresh() }}
					/>
				</View>
			</View>
		)
	}
	// 列表
	_renderListItem = (data) => {
		let { companyIndex } = this.state;
		let { companyName, corpTypeName, companyId, isForeign } = data.item;
		if (corpTypeName) {
			corpTypeName = corpTypeName.replace(/\,/g, '|')
		}
		return (
			<TouchableOpacity activeOpacity={1} onPress={() => {
				this.props.navigation.navigate('clientFundsDetail', {
					companyIndex: companyIndex,
					companyId: companyId,
					companyName: companyName,
					isForeign: isForeign,
					callback: () => this.reloadPage()
				})
			}} style={{}}>
				<View style={{ backgroundColor: '#fff' }}>
					<View style={styles.billNumWrap}>
						<View style={styles.billNumWrapTop}>
							<View>
								<Image source={require('../../../imgs/circle.png')} style={styles.circle} />
								<Text style={styles.nameType}>{companyName.substr(0, 1)}</Text>
							</View>
							<View style={{ flex: 1 }}>
								<Text style={styles.commonTitleTop}>{companyName || '-'}</Text>
								<Text style={styles.commonTopRight}>{corpTypeName}</Text>
							</View>
						</View>
					</View>
				</View>

			</TouchableOpacity>
		)
	}

	render() {
		let { status, listData, refreshIcon, choice, options, alertShow } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.headBox}>
					{this._renderSearchWarp()}
				</View>

				{
					status == 'data' ? (
						<View style={{ flex: 1, paddingBottom: 10 * scale }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>) : null
				}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />) : null
				}
				<SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false, companyIndex: val.selectIndex }, () => {
							this.props.navigation.setParams({
								choice: val || options[0]
							});
							this.initPage();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	headerWrap: {
		backgroundColor: style.color.themeColor,
		paddingLeft: 17 * scale,
		paddingRight: 17 * scale,
		paddingBottom: 20 * scale,
	},
	filterWrap: {
		marginTop: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		position: 'relative',
	},
	searchInput: {
		height: 38 * scale,
		// flex:1,
		width: 280 * scale,
		// paddingLeft: 42 * scale,
		// paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .33)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
		fontSize: 14 * scale,
		textAlign: 'center'

	},
	searchIcon: {
		width: 22 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 52 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	billNumWrap: {
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingVertical: 16 * scale,
	},
	circle: {
		width: 36 * scale,
		height: 36 * scale,
		marginRight: 14 * scale,

	},
	nameType: {
		fontSize: 14 * scale,
		color: '#5490EC',
		fontWeight: '600',
		position: 'absolute',
		left: 11 * scale,
		top: 11 * scale
	},
	billInfoWrap: {
		flexDirection: 'column',
		alignItems: 'flex-start',
		justifyContent: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 24 * scale,
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		paddingBottom: 18 * scale
	},
	commonTitle: {
		flex: 1,
		color: '#708090',
		fontSize: 12 * scale,
		minWidth: 64 * scale,
	},
	commonTitleTop: {
		flex: 1,
		fontWeight: '600',
		color: '#000',
		fontSize: 14 * scale,
		minWidth: 64 * scale,
	},
	commonTopRight: {
		fontSize: 12 * scale,
		marginTop: 8 * scale,
		color: '#34475F',
	},
	commonText: {
		flex: 1,
		fontSize: 13 * scale,
		color: '#0C0C0D',
		fontWeight: '700',
		paddingTop: 8 * scale,
	},
	buttonPass: {
		width: 68 * scale,
		backgroundColor: style.color.themeColor,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		marginRight: 14 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 68 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	titleText: {
		color: '#000',
		marginBottom: 10 * scale,
		fontSize: 14 * scale,
		fontWeight: '600'
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginTop: 10 * scale,
	},
	buttonRightBox: {
		flexDirection: 'row',
		// alignItems: 'center',
		justifyContent: 'center',
		marginTop: 5 * scale
	},
	accountSelect: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	billNumWrapTop: {
		flexDirection: 'row',
		alignItems: 'center',
		// justifyContent: 'space-between',
		// marginBottom:11*scale
	},
	buttonLeftText: {
		fontSize: 12,
		color: '#0E7FFD',
	},
	buttonLeftPass: {
		paddingVertical: 10 * scale,
		paddingHorizontal: 20 * scale,
		marginTop: -8 * scale
	},
	topRight: {
		fontSize: 14 * scale,
		color: '#fff',
		marginRight: 10 * scale
	},
	searchBox: {
		width: 330 * scale
	},
	headBox: {
		height: 75 * scale,
		backgroundColor: style.color.themeColor,
		// justifyContent:'center',
		alignItems: 'center'
	},
})